package com.project.common.orderby;

import com.project.common.exception.BusinessException;
import com.project.utils.StringUtils;
import lombok.Data;

import java.lang.reflect.Field;

@Data
public class OrderPattern {

    private String columnName;

    private Integer orderDirection;

    public static final int ORDER_BY_ASC = 0;
    public static final int ORDER_BY_DESC = 1;

    /**
     * 是否是字符串类型
     */
    private Boolean isStringType;

    /**
     * null值排在最前面或者最后面，null 普通排序，0，排在最前面 1 排在最后面
     */
    private Integer nullFirstOrLast;

    public static OrderPattern setOrderPattern(String columnName,Integer orderDirection,Class<?> pojoClass) {
        OrderPattern orderPattern = new OrderPattern();
        orderPattern.setColumnName(columnName);
        orderPattern.setOrderDirection(orderDirection);
        orderPattern.setIsStringType(isStringType(columnName,pojoClass));
        return orderPattern;
    }

    public static OrderPattern setOrderPattern(String columnName,Integer orderDirection) {
        OrderPattern orderPattern = new OrderPattern();
        orderPattern.setColumnName(columnName);
        orderPattern.setOrderDirection(orderDirection);
        return orderPattern;
    }

    public static Boolean isStringType(String key,Class<?> pojoClass) {
        if (key.contains(".")) {
            //处理t.*的情况
            key = key.substring(key.indexOf(".") + 1);
        }
        String keyName = StringUtils.lineToHump(key);
        Class clazz = null;
        try {
            clazz = getClass(pojoClass,keyName);
        } catch (Exception exception) {
            throw new BusinessException(key + "不合法");
        }

        if (clazz == null || String.class.equals(clazz)) {
            //默认当字符串处理
            return true;
        }
        return false;
    }

    private static Class getClass(Class c, String fieldName) {
        Field field = null;
        while (c != null) {
            Field[] fields = c.getDeclaredFields();
            if (fields != null && fields.length > 0) {
                for (int i = 0;i < fields.length;i++) {
                    Class clazz = fields[i].getType();
                    //这里临时先这么判断
                    if (clazz != null && clazz.getName().contains("OtcModel") || clazz.getName().contains("InvestmentIntentionModel")) {
                        clazz = getClass(clazz,fieldName);
                        if (clazz != null) {
                            return clazz;
                        }
                    }
                    if (fields[i].getName().equals(fieldName)) {
                        field = fields[i];
                        break;
                    }
                }
            }
            c = c.getSuperclass();
        }
        if (field == null) {
            return null;
        }
        return field.getType();
    }

}
